<script lang="ts">
import {defineComponent, type PropType, reactive, toRefs} from 'vue'
import {type CustomMenuItemProp, DEFAULT_CUSTOM_MENU_ITEM_PROP, type Menu} from "@/components/menuItem/types/menuItemTypes.ts";


export default defineComponent({
  name: 'menu-item',
  emits: ['checkItem'],
  props: {
    menu: {
      type: Object as PropType<Menu>,
      default: () => ({})
    },
    customProps: {
      type: Object as PropType<CustomMenuItemProp>,
      default: DEFAULT_CUSTOM_MENU_ITEM_PROP
    }
  },
  setup(props, {emit}) {
    const data = reactive({})
    const methods = {
      handleClick(menu: Menu) {
        emit("checkItem", menu)
      },
      checkItem(menu: Menu) {
        emit("checkItem", menu)
      },

      hasChildren(){
        return  props.menu.type === props.customProps.menuTypeValue && props.menu.children && props.menu.children.some(child => child.type === props.customProps.menuTypeValue)
      }
    }

    const validators = {}
    const rules = reactive({})
    const refs = {}

    return {
      ...toRefs(data),
      ...methods,
      validators,
      rules,
      ...refs,
    }
  }
})
</script>

<template>
  <el-sub-menu
      v-if="hasChildren()"
      :index="menu.id"
  >
    <template #title>
      <el-icon v-if="menu.icon">
        <component :is="menu.icon"/>
      </el-icon>
      <span>{{ menu.title }}</span>
    </template>
    <!-- 递归渲染子菜单 -->
    <menu-item
        v-for="child in menu.children"
        :key="child.id"
        :menu="child"
        @checkItem="checkItem"
    />
  </el-sub-menu>

  <!-- 如果是菜单（type: 0）但无 children，则是叶子菜单 -->
  <el-menu-item
      v-else-if="menu.type === 0"
      :index="menu.id"
      @click="handleClick(menu)"
  >
    <el-icon v-if="menu.icon">
      <component :is="menu.icon"/>
    </el-icon>
    <template #title>{{ menu.title }}</template>
  </el-menu-item>

</template>

<style scoped>

</style>